package com.yl.chainStore.util

import org.slf4j.LoggerFactory
import org.springframework.beans.BeansException
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Component
import java.io.IOException
import java.util.*
import javax.annotation.Resource
import kotlin.jvm.Throws


@Component("springBeanUtil")
class SpringBeanUtil {

	@Throws(BeansException::class)
	fun setApplicationContext(c: ApplicationContext) {
		ctx = c
	}

	fun getApplicationContext(): ApplicationContext {
		return ctx
	}
	companion object{
		private lateinit var ctx: ApplicationContext
		private val logger = LoggerFactory.getLogger(SpringBeanUtil::class.java)!!
		private val propMap: MutableMap<String,Properties> = mutableMapOf()


		fun <T> getBean(prop:String):T{
			val obj = ctx.getBean(prop)
			if (logger.isDebugEnabled) {
				logger.debug("property=[$prop],object=[$obj]");
			}
			return obj as T
		}

		fun  getProperties( filepath:String):Properties? {
			if (propMap.containsKey(filepath)){
				return propMap[filepath]
			}


			val resource = ctx.getResource(filepath)
			val prop = Properties()
			return try {
				prop.load(resource.getInputStream())
				propMap[filepath]= prop;
				prop
			} catch (e: IOException) {
				logger.error("can not find the resource file:[$filepath]",e)
				null

			}
		}

	}



}
